package com.fingersoft.feature.splash;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;

import com.fingersoft.business.BusinessContext;
import com.fingersoft.business.appupdate.IAppUpdateProvider;
import com.fingersoft.business.splash.Splash;
import com.fingersoft.business.welcome.IWelcomeProvider;
import com.fingersoft.common.ICommonCallback;
import com.fingersoft.cycle.IActivityCycle;
import com.fingersoft.dexload.DexLoadUtil;
import com.fingersoft.dexload.LunchModeHelper;
import com.fingersoft.feature.appupdate.CheckCallBack;
import com.fingersoft.feature.faceId.FaceIDExport;
import com.fingersoft.feature.loading.LoadingContext;
import com.fingersoft.feature.personal.api.UserDetailResponse2;
import com.fingersoft.im.MyApplication2;
import com.fingersoft.im.api.UserAgent;
import com.fingersoft.im.api.base.BaseModelCallback2;
import com.fingersoft.im.callback.AppConfigCallBack;
import com.fingersoft.im.utils.AppConfigUtils;
import com.fingersoft.im.utils.AppUtils;
import com.fingersoft.im.utils.JSONUtils;
import com.fingersoft.im.utils.UserInfoManager;
import com.fingersoft.util.UserInfoHelper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.BaseRequest;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.fingersoft.util.BuildConfigUtil;
import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public final class SealSplashContext implements ISplashContext {

    private final Application application;

    public SealSplashContext(Application application) {
        this.application = application;
    }

    @Override
    public boolean isDebug() {
        return AppUtils.DEBUG;
    }

    @Override
    public List<IActivityCycle> getActivityCycles() {
        ArrayList<IActivityCycle> activityCycles = new ArrayList<>();
        return activityCycles;
    }

    @Override
    public void onAfterEnsurePermission(Activity splashActivity, boolean useAdActivity, boolean checkVersionUpdate) {
        if (!checkVersionUpdate) {
            doNext(splashActivity, useAdActivity, true);
        } else {
            onAfterEnsurePermission(splashActivity, useAdActivity);
        }
    }
    //app检查更新
    @Override
    public void onAfterEnsurePermission(Activity splashActivity, boolean useAdActivity) {
        try {
            IAppUpdateProvider appUpdate = BusinessContext.Companion.getAppUpdate();
            if (appUpdate != null) {
                appUpdate.checkUpdate(splashActivity, false, new CheckCallBack() {
                    @Override
                    public void onCancel() {
                        doNext(splashActivity, useAdActivity, false);
                    }

                    @Override
                    public void onDownLoad(boolean isForcely) {
                        MyApplication2 myApplication = (MyApplication2) splashActivity.getApplication();
                        myApplication.setCanDisconnectVpn(false);
                        if (isForcely || BuildConfigUtil.INSTANCE.getBoolean("appWidgetBack2Source")) {
                            splashActivity.finish();
                        } else {
                            doNext(splashActivity, useAdActivity, false);
                        }
                    }

                    @Override
                    public void onNowVersion() {
                        doNext(splashActivity, useAdActivity, false);
                    }

                    @Override
                    public void onError() {
                        doNext(splashActivity, useAdActivity, false);
                    }


                    @Override
                    public void onNewVersion() {

                    }
                });
            } else {
                doNext(splashActivity, useAdActivity, false);
            }

        } catch (Exception e) {
            doNext(splashActivity, useAdActivity, false);
            e.printStackTrace();
        }
    }


    public void doNext(Activity splashActivity, boolean useAdActivity, boolean usePreConfig) {
        SharedPreferences sp = splashActivity.getSharedPreferences("app_info", MODE_PRIVATE);
        boolean isFirstLaunch = sp.getBoolean("isFirstLaunch", true);
        //应用安装/更新后，首次打开,进入欢迎页面
        if ((isFirstLaunch || (BuildConfigUtil.INSTANCE.getBoolean("welcomeWhenUpgrade") && AppUtils.isUpgrade()))
            && AppUtils.useWelcome()) {
            IWelcomeProvider welcome = BusinessContext.Companion.getWelcome();
            if (welcome != null) {
                welcome.start(splashActivity, false, false, usePreConfig);
            }
            splashActivity.finish();
        } else {
            //打开登陆页
            if (!useAdActivity) {
                LoadingContext.instance.doEnter(splashActivity, usePreConfig);
                return;
            }
            //打开广告页
            LoadingContext.instance.toLoading(splashActivity);
        }
        //保存版本号
        if (AppUtils.isUpgrade()) {
            AppUtils.recordVersion();
        }
    }

    @Override
    public void onFirstLaunch(Activity splashActivity) {

    }

    @Override
    public void onCreate(Activity splashActivity) {
        // 判断是否需要重新登录
        if (AppUtils.reloginWhenUpgrade() && AppUtils.isUpgrade()) {
            try {
                AppUtils.logout(splashActivity);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    @NonNull
    @Override
    public List<String> getEnsurePermissions() {

        ArrayList<String> list = new ArrayList<>(0);
        list.addAll(Splash.INSTANCE.getEnsurePermissions());
        if (BuildConfigUtil.INSTANCE.getBoolean("usePhoneStatePermForcely", true)) {
            list.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (BuildConfigUtil.INSTANCE.getBoolean("useExtStoragePermForcely", true)) {
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            list.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        return list;
    }

    @Override
    public void refreshUserInfo() {
        OkGo.post(AppUtils.getApiUrl("i/user/userInfo", AppUtils.J_ECODE))
            .headers("Emp-Info", JSONUtils.toJsonString(new UserAgent(AppUtils.getTokenInfo().getUserToken(), AppUtils.getTokenInfo().getDid())))
            .upJson("")
            .execute(new BaseModelCallback2<UserDetailResponse2>(UserDetailResponse2.class) {
                @Override
                public void onSuccess(UserDetailResponse2 userDetailResponse2, Call call, Response response) {
                    super.onSuccess(userDetailResponse2, call, response);
                    try {
                        UserInfoManager.INSTANCE.saveCurrentUserInfo(UserInfoHelper.convertUserInfo(userDetailResponse2.getData(), application));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    FaceIDExport.Companion.moduleSecInit();
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                }

                @Override
                public void onBefore(BaseRequest request) {
                    super.onBefore(request);
                }

                @Override
                public void onAfter(UserDetailResponse2 userDetailResponse2, Exception e) {
                    super.onAfter(userDetailResponse2, e);
                }
            });
    }

    @Override
    public void updateAppConfig(Context context, ICommonCallback commonCallback) {
        AppConfigUtils.getAppConfig(context, new AppConfigCallBack() {
            @Override
            public void onSuccess(String res) {
                if (null != commonCallback) {
                    commonCallback.onSuccess(res);
                }
            }

            @Override
            public void onError(String err) {
                if (null != commonCallback) {
                    commonCallback.onError(err);
                }
            }
        });
    }

    @Override
    public boolean getIsAppFirstOpen() {
        return LunchModeHelper.getInstance().isFirstOpen();
    }

    @Override
    public boolean getIfNeedDexPreload(WeakReference<Context> contextReference) {
        return DexLoadUtil.getInstance().getIfNeedDexPreLoad(contextReference);
    }

    @Override
    public void setIfNeedDexPreload(WeakReference<Context> contextReference, boolean newStatus) {
        DexLoadUtil.getInstance().setIfNeedDexPreLoad(contextReference, false);
    }
}
